package lol.clann.minecraft.springboot.plugin.bukkit.command.resolver.factory;

import lol.clann.minecraft.springboot.api.bukkit.command.resolver.CommandResolver;
import lol.clann.minecraft.springboot.api.bukkit.command.resolver.CommandResolverFactory;
import org.bukkit.command.CommandException;
import org.springframework.stereotype.Component;

/**
 *
 * @author pyz
 * @date 2019/5/6 9:29 PM
 */
@Component
public class EnumCommandResolverFactory implements CommandResolverFactory {
    @Override
    public boolean canResolve(Class<?> type) {
        return Enum.class.isAssignableFrom(type);
    }

    @Override
    public CommandResolver getResolver(Class<?> t) {
        return (sender, arg, type) -> {
            try {
                return Enum.valueOf((Class) type, arg);
            } catch (NullPointerException | IllegalArgumentException e) {
                Class clazz = (Class) type;
                Object[] enums = clazz.getEnumConstants();
                StringBuilder sb = new StringBuilder();
                sb.append("参数 ").append(arg).append(" 无效,可选值:");
                for (Object anEnum : enums) {
                    sb.append(anEnum).append(",");
                }
                throw new CommandException(sb.toString());
            }
        };
    }
}
